#include <stdio.h>
#include <string>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <functional>

namespace ThreadModule
{
    static int number = 1;

    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    template<typename T>
    class Thread
    {
        using func_t = std::function<void(T&)>;
    private:
        //成员方法
        static void* Routine(void* args)
        {
            Thread<T>* t = static_cast<Thread<T>* >(args);
            t->_status = TSTATUS::RUNNING;
            t->_func(t->_data);
            return nullptr;
        }

        void EnableDetach()
        {
            _joinable = false;
        }
    public:
        Thread(func_t func, T& data)
            :_func(func)
            ,_joinable(true)
            ,_data(data)
            ,_status(TSTATUS::NEW)
        {
            _name = "Thread - " + std::to_string(number++);
            _pid = getpid();
        }

        bool Start()
        {
            if(_status != TSTATUS::RUNNING)
            {
                int n = pthread_create(&_tid, nullptr, Routine, this);
                if(n != 0)
                    return false;
                return true;
            }
            return false;
        }

        bool Stop()
        {
            if(_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }

            return true;
        }

        bool Join()
        {
            if(_joinable)
            {
                int n = ::pthread_join(_tid, nullptr);
                if(n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }

            return true;
        }

        bool IsJoinbale()
        {
            return _joinable;
        }

        std::string Name()
        {
            return _name;
        }

        ~Thread()
        {

        }
    private:
        pid_t _pid;
        pthread_t _tid;
        std::string _name;
        bool _joinable; //是否是分离
        TSTATUS _status;
        func_t _func;
        T &_data;

    };
}